﻿package code {
	import flash.display.Shape;
	import flash.display.Sprite;
	import flash.geom.*;
	// derived from Schwartz's code
	// creates a vertex with x and y coordinate
	public class Vertex extends Sprite{
		public var angle:int;	// the angle that the web is drawn at
		public var level:int;	// the level the web is in
		public var vx:Number = 0;	// current velocity in the x direction
		public var vy:Number = 0;	// current velocity in the y direction
		public var alreadyChecked:Boolean; // if the vertex is to be checked
		public var wireList:Array;  // list of the wires
		public var startPosX:Number; // original start position
		public var startPosY:Number;
		private const SPRING:Number = .25;  // spring constant
		private const FRICTION:Number = .95;  // frcition constant
		private var checkVertex:Boolean;
		
		public function Vertex(x:Number, y:Number, angle:int, level:int) {
			this.x = x;
			this.y = y;
			
			this.angle = angle;
			this.level = level;
			
			alreadyChecked = false;
			wireList = new Array();
			startPosX = x;
			startPosY = y;
			if(level == 1)
				checkVertex = true;
			else
				checkVertex = false;
		}
		
		// adds wires to the list of wires for the vertices
		public function addWire(wire:Wire){
			if(!doesContain(wire)){
				wireList.push(wire);
			}
		}
		
		// checks to see if wires are already in the wire list
		public function doesContain(wire:Wire):Boolean{
			for each(var w:Wire in wireList){
				if(wire == w){
					return true;
				}
			}
			return false;
		}
		
		// checks and adjusts the springs movement
		public function checkSprings(timeDifference:Number){
			if(timeDifference > 1) // fixes error on unpause
				timeDifference = 1;
			
			if(!alreadyChecked && !checkVertex){
				for each(var w:Wire in wireList){
					var tempVertex = findAdjacentVertex(w);
					var dx:Number = tempVertex.x - x;  // total difference between the vertices
					var dy:Number = tempVertex.y - y;  
					var tempAngle = Math.atan2(dy, dx); // angle between them
					var targetX:Number = tempVertex.x - Math.cos(tempAngle)  * w.startDist;  // the target position to go to based on original length of string
					var targetY:Number = tempVertex.y - Math.sin(tempAngle) * w.startDist;
					vx += (targetX - x) * SPRING * timeDifference;  // adjusts the amount to go based on time and spring constant
					vy += (targetY - y) * SPRING * timeDifference;
				
					vx *= FRICTION;  // friction for dampening
					vy *= FRICTION;
					x += vx * timeDifference; // adjusts the amount to go by time again
					y += vy * timeDifference;
				}
			}
			
		}
		
		// finds the adjacent vertices based on the wires
		public function findAdjacentVertex(w:Wire):Vertex{
			if(w.a == this)
				return w.b;
			else if(w.b == this)
				return w.a;
			return null;
		}
		

	}
	
}
